package co.yixiang.weixin.biz.service;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import co.yixiang.common.core.constant.ShopConstants;
import co.yixiang.common.redis.utils.RedisUtils;
import co.yixiang.weixin.common.weixin.vo.LoginParam;
import co.yixiang.weixin.biz.config.WxMaConfiguration;
import co.yixiang.weixin.biz.config.WxMpConfiguration;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class WxOauthService {

    @Autowired
    private RedisUtils redisUtils;
    /**
     * 小程序登录
     * @param loginParam
     * @return
     */
    public WxMaUserInfo wxMaOauthService(LoginParam loginParam){
        String code = loginParam.getCode();
        String encryptedData = loginParam.getEncryptedData();
        String iv = loginParam.getIv();

        WxMaService wxMaService = WxMaConfiguration.getWxMaService();
        WxMaJscode2SessionResult session = null;
        try {
            session = wxMaService.getUserService().getSessionInfo(code);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        WxMaUserInfo wxMpUser = wxMaService.getUserService()
                .getUserInfo(session.getSessionKey(), encryptedData, iv);

        redisUtils.set(ShopConstants.YSHOP_MINI_SESSION_KET + wxMpUser.getOpenId(), session.getSessionKey());
        return wxMpUser;
    }

    /**
     * 微信公众号授权登录
     * @param code
     * @return
     */
    public WxMpUser wxMpOauthService(String code){
        WxMpService wxService = WxMpConfiguration.getWxMpService();
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken;
        WxMpUser wxMpUser = new WxMpUser();
        try {
            wxMpOAuth2AccessToken = wxService.getOAuth2Service().getAccessToken(code);
            wxMpUser = wxService.getOAuth2Service().getUserInfo(wxMpOAuth2AccessToken, null);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        return wxMpUser;
    }



}
